﻿﻿package com.glidecast.controllers
{
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import flash.net.URLVariables;

	import com.glidecast.models.Content;
	import com.glidecast.models.RSSItem;

	import com.glidecast.controllers.RSSItemController;	
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	public class ContentController  extends EventDispatcher
	{
		private var ldr:URLLoader=new URLLoader;
		public static var COMPLETE:String='ContentDownloadComplete';
		
		public function ContentController()
		{	
		}
		private var _content:Content;
		public function get content():Content
		{
			return _content;
		}
		public function set content(s:Content):void
		{
			_content=s;
		}
		public function load():void
		{	
			if (this._content == null)
				return;
			var urlReq:URLRequest = new URLRequest(this._content.url);
			ldr.addEventListener("complete", contentLoaded);
			ldr.load(urlReq);
			trace("Requesting updated content for " + this._content.url);
		}
		public function contentLoaded(event:Event):void 
		{
			try
			{
			//now that the content is downloaded, it needs to 
			//be made renderable.

			//get the gdf xml from the response
			var loader:URLLoader = URLLoader(event.target);
			
			//convert to an xml object
			var contentXML:XML = XML(loader.data);
			
			// The channel itself has a title, pass that to the 
			// content object.
			this._content.title = contentXML.channel.title;
			
			//prime the content's rssItems
			var rssArray:Array = new Array();
						
			for each (var vRSSItem:XML in contentXML.channel.item)
			{
				var tvRSSItem:RSSItem = new RSSItem();
				tvRSSItem.title = vRSSItem.title;
				tvRSSItem.description = vRSSItem.description;
				
				//not going to worry about enclosure type. Too many potential problems.
				//the controller will need to deal with it.
				try
				{
				tvRSSItem.enclosureurl = vRSSItem.enclosure.@url;
				}
				catch(error:Error)
				{
					trace(error);
				}
				var tvRSSItemController:RSSItemController = new RSSItemController();
				tvRSSItemController.rssitem = tvRSSItem;
				tvRSSItemController.load();
				rssArray.push(tvRSSItem);
			}	
			this._content.RSSItems = new Array();		
			this._content.RSSItems = rssArray;
			
			dispatchEvent(new Event(ContentController.COMPLETE));
			
			trace("Loaded content");
			}
			catch(error:Error)
			{
				trace("Error downloading content " + error);
			}
		}
		
	}
}
